# HG changeset patch # User Ludovic Chabant # Date 1692035095 25200 # Node ID 8be02002ed66e55f4d4b1a41cca4f8d17665ac0f # Parent 16d304d586b1b37765d95018d31a569c2e1c049f Use Obsidian's view APIs for scrolling state Obsidian does some asynchronous formatting upon opening a file which can affect the vertical positioning of things, especially when there are tables for instance. Setting the scrolling position via the CM6 APIs gets invalidated by this, so we're using the Obsidian view API instead even if it only allows getting/setting vertical scrolling (not horizontal). diff -r 16d304d586b1 -r 8be02002ed66 src/main.ts --- a/src/main.ts Mon Aug 14 10:42:21 2023 -0700 +++ b/src/main.ts Mon Aug 14 10:44:55 2023 -0700 @@ -278,14 +278,15 @@ } private readonly rememberFileState = async (file: TFile, view: MarkdownView): Promise => { - const scrollInfo = view.editor.getScrollInfo(); + // Save scrolling position (Obsidian API only gives vertical position). + const scrollInfo = {top: view.currentMode.getScroll(), left: 0}; + + // Save current selection. + // If state selection is undefined, we have a legacy editor. Just ignore that part. const cm6editor = view.editor as EditorWithCM6; const stateSelection: EditorSelection = cm6editor.cm.state.selection; - if (stateSelection == undefined) { - // Legacy editor is in use, let's ignore - return; - } - const stateSelectionJSON = stateSelection.toJSON(); + const stateSelectionJSON = (stateSelection !== undefined) ? stateSelection.toJSON() : ""; + const stateData = {'scrollInfo': scrollInfo, 'selection': stateSelectionJSON}; var existingFile = this.data.rememberedFiles[file.path]; @@ -312,12 +313,18 @@ if (existingFile) { console.debug("RememberedFileState: restoring state for:", file.path, existingFile.stateData); const stateData = existingFile.stateData; - view.editor.scrollTo(stateData.scrollInfo.left, stateData.scrollInfo.top); - const cm6editor = view.editor as EditorWithCM6; - var transaction = cm6editor.cm.state.update({ - selection: EditorSelection.fromJSON(stateData.selection)}) - - cm6editor.cm.dispatch(transaction); + + // Restore scrolling position (Obsidian API only allows setting vertical position). + view.currentMode.applyScroll(stateData.scrollInfo.top); + + // Restore last known selection, if any. + if (stateData.selection != "") { + const cm6editor = view.editor as EditorWithCM6; + var transaction = cm6editor.cm.state.update({ + selection: EditorSelection.fromJSON(stateData.selection)}) + + cm6editor.cm.dispatch(transaction); + } } }